package com.apache.audit.service.impl;

import com.apache.api.manager.PluginConnector;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.database.constant.Validator;
import com.apache.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 */
public class AuditProxyManagerImpl implements ProxyManager {

    private Logger log = LoggerFactory.getLogger(AuditProxyManagerImpl.class);

    protected Map<String, List<PluginConnector>> plugins = new HashMap<String, List<PluginConnector>>();

    public void setPlugins(Map<String, List<PluginConnector>> plugins) {
        this.plugins = plugins;
    }

    /**
     * description:代理执行方法(带事务)
     *
     * @param vo 方法参数
     * @return
     */
    public Object saveInvoke(ParamsVo vo) throws BusinessException {
        String key = vo.getKey();
        if (!Validator.isEmpty(plugins) && !Validator.isEmpty(plugins.get(key))) {
            Object result = null;
            try {
                for (PluginConnector plugin : plugins.get(key)) {
                    result = plugin.execute(vo);
                }
            } catch (Exception e) {
                log.error("异常",e);
                throw new BusinessException("执行出错", e);
            }
            return result;
        }
        return null;
    }

    /**
     * description:代理执行方法(不带事务)
     *
     * @param vo 方法参数
     * @return
     */
    public Object doInvoke(ParamsVo vo) throws BusinessException {
        String key = vo.getKey();
        if (!Validator.isEmpty(plugins) && !Validator.isEmpty(plugins.get(key))) {
            Object result = null;
            try {
                for (PluginConnector plugin : plugins.get(key)) {
                    result = plugin.execute(vo);
                }
            } catch (Exception e) {
                log.error("异常",e);
                throw new BusinessException("执行出错", e);
            }
            return result;
        }
        return null;
    }

}
